﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using wxtools.Objects;
using System.Drawing.Drawing2D;

namespace wxtools
{
    public partial class frmMain : Form
    {
        private WxUtils wxutils = new WxUtils();

        public frmMain()
        {
            InitializeComponent();
        }

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    string url = "https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=" + WxTools.GetTimeStamp(DateTime.Now);
        //    string html = WxTools.HttpGet(url, "");
        //    //window.QRLogin.code = 200; window.QRLogin.uuid = "AZ4OWTeelA==";
        //    Regex reg = new Regex("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(.*?)\"");
        //    Match mc = reg.Match(html);
        //    if (mc.Success && mc.Groups.Count == 3 && mc.Groups[1].Value == "200")
        //    {
        //        WxConfig.uuid = mc.Groups[2].Value;
        //        loginQrCode.ImageLocation = string.Format("https://login.weixin.qq.com/qrcode/{0}?t=webwx", WxConfig.uuid);
        //        loginQrCode.Visible = true;
        //        timer1.Enabled = true;
        //    }
        //    else
        //    {
        //        loginQrCode.Visible = false;
        //        timer1.Enabled = false;
        //    }
        //}

        //private void timer1_Tick(object sender, EventArgs e)
        //{
        //    string url = string.Format("https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=1&_={1}", WxConfig.uuid, WxTools.GetTimeStamp(DateTime.Now));
        //    string html = WxTools.HttpGet(url, "");
        //    Regex reg = new Regex("window.code=(\\d+);");
        //    Match mc = reg.Match(html);
        //    //txtLoger.Text += html + "\r\n";
        //    if (mc.Success && mc.Groups.Count == 2 && mc.Groups[1].Value == "201")
        //    {
        //        if (txtLoger.Text.IndexOf("成功扫描,请在手机上点击确认以登录") == -1)
        //        {
        //            txtLoger.Text += "成功扫描,请在手机上点击确认以登录" + "\r\n";

        //            string base64_image = html.Split(new string[] { "\'" }, StringSplitOptions.None)[1].Split(',')[1];
        //            byte[] base64_image_bytes = Convert.FromBase64String(base64_image);
        //            MemoryStream memoryStream = new MemoryStream(base64_image_bytes, 0, base64_image_bytes.Length);
        //            memoryStream.Write(base64_image_bytes, 0, base64_image_bytes.Length);
        //            //转成图片
        //            loginQrCode.Image = Image.FromStream(memoryStream);
        //            memoryStream.Close();
        //        }
        //        //window.userAvatar = 'data
        //    }
        //    if (mc.Success && mc.Groups.Count == 2 && (mc.Groups[1].Value == "408" || mc.Groups[1].Value == "0"))
        //    {
        //        txtLoger.Text += "超时" + "\r\n";
        //        timer1.Enabled = false;
        //        loginQrCode.Visible = false;
        //        button1_Click(null, null);
        //    }
        //    else if (mc.Success && mc.Groups.Count == 2 && mc.Groups[1].Value == "200")
        //    {
        //        timer1.Enabled = false;
        //        txtLoger.Text += "微信登陆登陆成功\r\n";
        //        mc = new Regex("window.redirect_uri=\"(\\S+?)\";").Match(html);
        //        //txtLoger.Text += "登陆成功,window.redirect_uri:" + mc.Groups[1].Value + "\r\n";
        //        WxConfig.redirect_uri = mc.Groups[1].Value + "&fun=new";
        //        WxConfig.base_uri = WxConfig.redirect_uri.Substring(0, WxConfig.redirect_uri.LastIndexOf("/"));
        //        //https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=03f725a8039d418ab79c69b6ffbd771b&lang=zh_CN&scan=1388975896&fun=new
        //        var services = new List<string[]>(){
        //            new string[2]{"wx2.qq.com", "webpush2.weixin.qq.com"},  
        //            new string[2]{"qq.com", "webpush.weixin.qq.com"},  
        //            new string[2]{"web1.wechat.com", "webpush1.wechat.com"},  
        //            new string[2]{"web2.wechat.com", "webpush2.wechat.com"},  
        //            new string[2]{"wechat.com", "webpush.wechat.com"},  
        //            new string[2]{"web1.wechatapp.com", "webpush1.wechatapp.com"}
        //        };
        //        WxConfig.push_uri = WxConfig.base_uri;
        //        foreach (string[] item in services)
        //        {
        //            if (WxConfig.base_uri.IndexOf(item[0]) >= 0)
        //            {
        //                WxConfig.push_uri = string.Format("https://{0}/cgi-bin/mmwebwx-bin", item[1]);
        //                break;
        //            }
        //        }
        //        //txtLoger.Text += "登陆成功,push_uri:" + WxConfig.push_uri + "\r\n";

        //        html = WxTools.HttpGetCookies(WxConfig.redirect_uri, "");
        //        wxutils.webwxinit(html);
        //        WxConfig.isLogin = true;
        //        button1.Visible = false;

        //        WxConfig.MemberList = wxutils.webwxgetcontact();

        //        txtLoger.Text += "获取联系人成功，共用" + WxConfig.MemberList.Count + "位好友\r\n";
        //        //<error><ret>0</ret><message></message><skey>@crypt_7855a35a_7bfa4697173dedc47bb76c829b8c7c8f</skey><wxsid>/hXvUPx3ExhehKJm</wxsid><wxuin>2235275221</wxuin><pass_ticket>H9yqQuWyFlTzBgMsKkMibnjdcMrcU3TqKtw7zdzrL4eMPT6F%2F6wsBAKsU2psUK5h</pass_ticket><isgrayscale>1</isgrayscale></error>
        //    }
        //    //{"BaseRequest":{"Uin":0,"Sid":0},"Count":1,"List":[{"Type":1,"Text":"/cgi-bin/mmwebwx-bin/login, First Request Success, uuid: 454d958c7f6243"}]}
        //}

        frmProgress f;
        private void button2_Click(object sender, EventArgs e)
        {
            //string html = "{\"BaseRequest\":{\"Uin\":0,\"Sid\":0},\"Count\":1,\"List\":[{\"Type\":1,\"Text\":\"/cgi-bin/mmwebwx-bin/login, First Request Success, uuid: 454d958c7f6243\"}]}";
            //JObject json = JObject.Parse(resultData);
            //getSkey();
            //WxSync();
            System.Threading.Thread th = new System.Threading.Thread(checkFriend);
            th.IsBackground = true;
            th.Start();

            f = new frmProgress();
            f.ShowDialog();
        }

        /// <summary>
        /// 监测好友
        /// </summary>
        private void checkFriend()
        {
            this.button2.Invoke((Action)delegate { button2.Enabled = false; });
            List<string> UserNames = new List<string>();
            WxConfig.BlockedList.Clear();
            WxConfig.DeletedList.Clear();
            //种子群成员
            List<JObject> seed = new List<JObject>();
            List<string> seedUserNames = new List<string>();
            while (string.IsNullOrEmpty(WxConfig.ChatRoomName))
            {
                seedUserNames.Clear();
                UserNames.Clear();
                //随机抽取两个人建群
                seed = WxConfig.MemberList.OrderBy(r => Guid.NewGuid()).Take(2).Select(r => r.Value).ToList();
                foreach (JObject item in seed)
                {
                    UserNames.Add(item.GetValue("UserName") + "");
                    seedUserNames.Add(item.GetValue("UserName") + "");
                }
                //txtLoger.Text += "开始创建群聊\r\n";
                bool ret = wxutils.createChatroom(UserNames);
                if (ret)
                {
                    //txtLoger.Text += "创建群聊成功" + WxConfig.ChatRoomName + "\r\n";
                    this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "创建群聊成功" + WxConfig.ChatRoomName + "\r\n"; });
                    break;
                }
                if (string.IsNullOrEmpty(WxConfig.ChatRoomName))
                {
                    //txtLoger.Text += "创建群聊失败" + WxConfig.ChatRoomName + "正在重试\r\n";
                    this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "创建群聊失败" + WxConfig.ChatRoomName + "正在重试\r\n"; });
                }
            }

            List<JObject> mlist = WxConfig.MemberList.Where(r => !UserNames.Contains(r.Key)).Select(r => r.Value).ToList();
            int group_num = (int)Math.Ceiling(mlist.Count * 1.0 / WxConfig.MAX_GROUP_NUM);
            int progress = 0;
            int maxcount = mlist.Count;
            if (maxcount == 0)
            {
                return;
            }
            for (int i = 0; i < group_num; i++)
            {
                UserNames.Clear();
                for (int j = 0; j < WxConfig.MAX_GROUP_NUM; j++)
                {
                    if (i * WxConfig.MAX_GROUP_NUM + j >= mlist.Count)
                    {
                        break;
                    }
                    progress++;
                    JObject user = mlist[i * WxConfig.MAX_GROUP_NUM + j];
                    UserNames.Add(user.GetValue("UserName") + "");
                }
                //txtLoger.Text += "开始群聊拉人\r\n";
                //this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "开始群聊拉人\r\n"; });
                bool ret = wxutils.addMember(UserNames);
                if (!ret)
                {
                    //txtLoger.Text += "群聊拉人成功\r\n";
                    this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "群聊拉人失败\r\n"; });
                }
                //txtLoger.Text += "当前进度" + (Math.Round(progress * 100m / maxcount)) + "%\r\n";
                //this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "当前进度" + (Math.Round(progress * 100m / maxcount)) + "%\r\n"; });
                this.txtLoger.Invoke((Action)delegate
                {
                    if (f != null)
                    {
                        f.setValue((int)Math.Round(progress * 100m / maxcount), "群聊拉人成功" + WxConfig.ChatRoomName + "");
                    }
                    //txtLoger.Text += "开始创建群聊\r\n";
                });
                //删除群成员
                if (!wxutils.deleteMember(UserNames))
                {
                    //txtLoger.Text += "群聊删人成功" + WxConfig.ChatRoomName + "\r\n";
                    this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "群聊删人失败" + WxConfig.ChatRoomName + "\r\n"; });
                }
                System.Threading.Thread.Sleep(1000);
            }
            if (!wxutils.deleteMember(seedUserNames))
            {
                //txtLoger.Text += "群聊删人成功" + WxConfig.ChatRoomName + "\r\n";
                this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "群聊删人失败" + WxConfig.ChatRoomName + "\r\n"; });
            }
            //txtLoger.Text += "共有" + WxConfig.DeletedList.Count + "个好友删除你\r\n";
            this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "共有" + WxConfig.DeletedList.Count + "个好友删除你\r\n"; });
            foreach (var item in WxConfig.DeletedList)
            {
                KeyValuePair<string, JObject> u = WxConfig.MemberList.Where(r => r.Key == item).FirstOrDefault();
                if (u.Value != null)
                {
                    this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "" + u.Value.GetValue("NickName") + "，"; });
                    wxutils.webWxOplog(u.Value.GetValue("UserName").ToString(), "AAA" + u.Value.GetValue("NickName") + "-删除");
                    System.Threading.Thread.Sleep(300);
                }
            }
            //txtLoger.Text += "\r\n共有" + WxConfig.BlockedList.Count + "个好友拉黑你或异常\r\n";
            this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "\r\n共有" + WxConfig.BlockedList.Count + "个好友拉黑你或异常\r\n"; });
            foreach (var item in WxConfig.BlockedList)
            {
                KeyValuePair<string, JObject> u = WxConfig.MemberList.Where(r => r.Key == item).FirstOrDefault();
                if (u.Value != null)
                {
                    //txtLoger.Text += "" + u.Value.GetValue("NickName") + "，";
                    this.txtLoger.Invoke((Action)delegate { txtLoger.Text += "" + u.Value.GetValue("NickName") + "，"; });
                    wxutils.webWxOplog(u.Value.GetValue("UserName").ToString(), "AAA" + u.Value.GetValue("NickName") + "-拉黑(异常)");
                    System.Threading.Thread.Sleep(300);
                }
            }
            this.button2.Invoke((Action)delegate
            {
                button2.Enabled = true;
                f.Close();
                f = null;
            });
        }

        private void txtLoger_TextChanged(object sender, EventArgs e)
        {
            txtLoger.SelectionStart = txtLoger.Text.Length; //Set the current caret position at the end
            txtLoger.ScrollToCaret(); //Now scroll it automatically
        }

        /// <summary>
        /// 加载好友
        /// </summary>
        private void LoadFriends()
        {
            WxConfig.MemberList.Clear();
            this.txtLoger.Invoke((Action)delegate()
            {
                txtLoger.Text += "正在加载通讯录" + "\r\n";
            });
            int seq = 0;
            this.txtLoger.Invoke((Action)delegate()
            {
                txtLoger.Text += "正在加载通讯录seq" + seq + "\r\n";
            });
            Dictionary<string, JObject> ret = wxutils.webwxgetcontact(ref seq);
            foreach (var item in ret)
            {
                WxConfig.MemberList.Add(item.Key, item.Value);
            }
            while (seq > 0)
            {
                this.txtLoger.Invoke((Action)delegate()
                {
                    txtLoger.Text += "正在加载通讯录seq" + seq + "\r\n";
                });
                ret = wxutils.webwxgetcontact(ref seq);
                foreach (var item in ret)
                {
                    WxConfig.MemberList.Add(item.Key, item.Value);
                }
                System.Threading.Thread.Sleep(1000);
            }
            this.Invoke((Action)delegate()
            {
                txtLoger.Text += "共用联系人" + WxConfig.MemberList.Count + "个\r\n";
                //设置在ListView控件中显示的方式
                ImageList imageListSmall = new ImageList();   //产生图像对象
                //创建组
                ListViewGroup lvg = new ListViewGroup();
                lvg.Name = "我的好友";
                lvg.Header = "我的好友";
                lvg.HeaderAlignment = HorizontalAlignment.Left;
                foreach (var user in WxConfig.MemberList)
                {
                    JObject u = user.Value;
                    WxListBoxItem item = new WxListBoxItem();
                    //System.Drawing.Image src = wxutils.GetIcon(u.GetValue("UserName") + "");
                    //Bitmap bmp = new Bitmap(38, 38);
                    //Graphics g = Graphics.FromImage(bmp);
                    //g.Clear(Color.Transparent);
                    //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    //绘制图像
                    //g.DrawImage(src, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, src.Width, src.Height, GraphicsUnit.Pixel);
                    //g.DrawImage(src, 0, 0, src.Width, src.Height);
                    //g.Dispose();
                    //g.Dispose();
                    //item.Image = bmp;
                    item.IsClass = false;
                    item.Title = u.GetValue("RemarkName") + "";
                    item.Text = u.GetValue("Signature") + "";
                    item.Remarks = u.GetValue("NickName") + "";
                    item.IsExpand = false;
                    wxListBox1.Items.Add(item);
                    wxListBox1.Update();
                }
            });
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            System.Threading.Thread th = new System.Threading.Thread(syncThread);
            th.IsBackground = true;
            th.Start();
        }

        private void syncThread()
        {
            LoadFriends();
            while (true)
            {
                System.Threading.Thread.Sleep(1500);
                if (!WxConfig.isLogin)
                {
                    continue;
                }
                string sync_flag = wxutils.WxSyncCheck();  //同步检查
                if (sync_flag == null)
                {
                    continue;
                }
                //这里应该判断 sync_flag中selector的值
                else //有消息
                {
                    JObject sync_result = wxutils.WxSync();  //进行同步
                    if (sync_result != null)
                    {
                        if (sync_result["AddMsgCount"] != null && sync_result["AddMsgCount"].ToString() != "0")
                        {
                            foreach (JObject m in sync_result["AddMsgList"])
                            {
                                string from = m["FromUserName"].ToString();
                                string to = m["ToUserName"].ToString();
                                string content = m["Content"].ToString();
                                string type = m["MsgType"].ToString();

                                WXMsg msg = new WXMsg();
                                msg.From = from;
                                msg.Msg = type == "1" ? content : "请在其他设备上查看消息";  //只接受文本消息
                                msg.Readed = false;
                                msg.Time = DateTime.Now;
                                msg.To = to;
                                msg.Type = int.Parse(type);

                                if (msg.Type == 51)  //屏蔽一些系统数据
                                {
                                    continue;
                                }
                                this.BeginInvoke((Action)delegate()
                                {
                                    if (!msg.From.StartsWith("@@") && msg.From != WxConfig.MyUser.GetValue("NickName") + "" && WxConfig.MemberList.ContainsKey(msg.From))
                                    {
                                        txtLoger.Text += "接收到【" + WxConfig.MemberList[msg.From].GetValue("NickName") + "】发来的微信消息: " + content + "\r\n";
                                    }
                                    else if (msg.From.StartsWith("@@") && WxConfig.GroupList.ContainsKey(msg.From))
                                    {
                                        txtLoger.Text += "接收到群【" + WxConfig.GroupList[msg.From].GetValue("NickName") + "】消息: " + content + "\r\n";
                                    }
                                    //WXUser user; bool exist_latest_contact = false;
                                    //foreach (Object u in wChatList1.Items)
                                    //{
                                    //    user = u as WXUser;
                                    //    if (user != null)
                                    //    {
                                    //        if (user.UserName == msg.From && msg.To == _me.UserName)  //接收别人消息
                                    //        {
                                    //            wChatList1.Items.Remove(user);
                                    //            wChatList1.Items.Insert(0, user);
                                    //            exist_latest_contact = true;
                                    //            user.ReceiveMsg(msg);
                                    //            break;
                                    //        }
                                    //        else if (user.UserName == msg.To && msg.From == _me.UserName)  //同步自己在其他设备上发送的消息
                                    //        {
                                    //            wChatList1.Items.Remove(user);
                                    //            wChatList1.Items.Insert(0, user);
                                    //            exist_latest_contact = true;
                                    //            user.SendMsg(msg, true);
                                    //            break;
                                    //        }
                                    //    }
                                    //}
                                    //if (!exist_latest_contact)
                                    //{
                                    //    foreach (object o in wFriendsList1.Items)
                                    //    {
                                    //        WXUser friend = o as WXUser;
                                    //        if (friend != null && friend.UserName == msg.From && msg.To == _me.UserName)
                                    //        {
                                    //            wChatList1.Items.Insert(0, friend);
                                    //            friend.ReceiveMsg(msg);
                                    //            break;
                                    //        }
                                    //        if (friend != null && friend.UserName == msg.To && msg.From == _me.UserName)
                                    //        {
                                    //            wChatList1.Items.Insert(0, friend);
                                    //            friend.SendMsg(msg, true);
                                    //            break;
                                    //        }
                                    //    }
                                    //}
                                    //wChatList1.Invalidate();
                                });
                            }
                        }
                    }
                }
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }
    }
}
